#!/bin/bash
# scripts/monitor.sh - 系统监控和健康检查

set -e

# 配置
SERVICE_NAME="jfastfiler"
API_URL="http://localhost:8080"
HEALTH_URL="${API_URL}/api/v1/health"
METRICS_URL="http://localhost:9090/metrics"
ALERT_EMAIL="admin@example.com"
LOG_FILE="/opt/jfastfiler/logs/monitor.log"

# 颜色定义
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m'

log() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$LOG_FILE"
    echo -e "$2$1${NC}"
}

# 健康检查
health_check() {
    local response
    response=$(curl -s -o /dev/null -w "%{http_code}" "$HEALTH_URL" 2>/dev/null || echo "000")
    
    if [ "$response" -eq 200 ]; then
        log "健康检查通过" "$GREEN"
        return 0
    else
        log "健康检查失败，HTTP状态码: $response" "$RED"
        return 1
    fi
}

# 检查服务状态
check_service_status() {
    if systemctl is-active --quiet "$SERVICE_NAME"; then
        log "服务运行正常" "$GREEN"
        return 0
    else
        log "服务未运行" "$RED"
        return 1
    fi
}

# 检查资源使用情况
check_resources() {
    # 内存使用率
    local mem_usage
    mem_usage=$(free | awk 'NR==2{printf "%.2f", $3 * 100/$2}')
    
    # CPU使用率
    local cpu_usage
    cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d'%' -f1)
    
    # 磁盘使用率
    local disk_usage
    disk_usage=$(df /opt/jfastfiler | awk 'NR==2{print $5}' | cut -d'%' -f1)
    
    log "资源使用 - 内存: ${mem_usage}%, CPU: ${cpu_usage}%, 磁盘: ${disk_usage}%" "$YELLOW"
    
    # 检查阈值
    if (( $(echo "$mem_usage > 90" | bc -l) )); then
        log "警告: 内存使用率过高" "$RED"
        return 1
    fi
    
    if (( $(echo "$cpu_usage > 90" | bc -l) )); then
        log "警告: CPU使用率过高" "$RED"
        return 1
    fi
    
    if [ "$disk_usage" -gt 90 ]; then
        log "警告: 磁盘使用率过高" "$RED"
        return 1
    fi
    
    return 0
}

# 检查数据库
check_database() {
    local db_file="/opt/jfastfiler/data/filemanager.db"
    
    if [ ! -f "$db_file" ]; then
        log "错误: 数据库文件不存在" "$RED"
        return 1
    fi
    
    local db_size
    db_size=$(stat -c%s "$db_file" 2>/dev/null || stat -f%z "$db_file")
    local db_size_mb=$((db_size / 1024 / 1024))
    
    log "数据库大小: ${db_size_mb}MB" "$YELLOW"
    
    # 检查数据库完整性
    if command -v sqlite3 &> /dev/null; then
        if sqlite3 "$db_file" "PRAGMA integrity_check;" 2>/dev/null | grep -q "ok"; then
            log "数据库完整性检查通过" "$GREEN"
        else
            log "数据库完整性检查失败" "$RED"
            return 1
        fi
    fi
    
    return 0
}

# 发送警报
send_alert() {
    local subject="$1"
    local message="$2"
    
    if command -v mail &> /dev/null; then
        echo "$message" | mail -s "$subject" "$ALERT_EMAIL"
    fi
    
    # 也可以集成其他通知方式，如Slack、Telegram等
    log "警报发送: $subject" "$RED"
}

# 自动修复
auto_fix() {
    log "尝试自动修复..." "$YELLOW"
    
    # 重启服务
    if ! systemctl is-active --quiet "$SERVICE_NAME"; then
        log "重启服务..." "$YELLOW"
        systemctl start "$SERVICE_NAME"
        sleep 5
    fi
    
    # 检查是否需要清理临时文件
    local temp_size
    temp_size=$(du -sh /opt/jfastfiler/temp 2>/dev/null | cut -f1)
    if [ "$temp_size" != "0" ]; then
        log "清理临时文件..." "$YELLOW"
        find /opt/jfastfiler/temp -type f -mtime +1 -delete
    fi
}

# 生成报告
generate_report() {
    local report_file="/opt/jfastfiler/logs/monitor_report_$(date +%Y%m%d).log"
    
    {
        echo "=== JFastFiler 监控报告 ==="
        echo "生成时间: $(date)"
        echo "服务状态: $(systemctl is-active $SERVICE_NAME && echo '运行中' || echo '停止')"
        echo "运行时长: $(systemctl show -p ActiveEnterTimestamp $SERVICE_NAME | cut -d= -f2)"
        echo ""
        echo "资源使用情况:"
        free -h | head -2
        echo ""
        df -h /opt/jfastfiler
        echo ""
        echo "最近错误日志:"
        journalctl -u $SERVICE_NAME --since="1 hour ago" | grep -i error | tail -10
    } > "$report_file"
    
    log "监控报告已生成: $report_file" "$GREEN"
}

# 主监控循环
main_monitor() {
    local check_interval=${1:-300}  # 默认5分钟
    
    log "启动监控服务，检查间隔: ${check_interval}秒" "$GREEN"
    
    while true; do
        local issues=0
        
        log "=== 开始监控检查 ===" "$YELLOW"
        
        # 执行各项检查
        if ! check_service_status; then
            ((issues++))
            send_alert "JFastFiler服务停止" "服务未运行，请检查"
            auto_fix
        fi
        
        if ! health_check; then
            ((issues++))
            send_alert "JFastFiler健康检查失败" "API健康检查失败"
        fi
        
        if ! check_resources; then
            ((issues++))
        fi
        
        if ! check_database; then
            ((issues++))
            send_alert "JFastFiler数据库问题" "数据库检查失败"
        fi
        
        # 生成每小时报告
        if [ "$(date +%M)" = "00" ]; then
            generate_report
        fi
        
        if [ $issues -eq 0 ]; then
            log "所有检查通过" "$GREEN"
        else
            log "发现 $issues 个问题" "$RED"
        fi
        
        log "等待 ${check_interval} 秒后再次检查..." "$YELLOW"
        sleep "$check_interval"
    done
}

# 单次检查
single_check() {
    log "执行单次检查..." "$YELLOW"
    
    local issues=0
    
    check_service_status || ((issues++))
    health_check || ((issues++))
    check_resources || ((issues++))
    check_database || ((issues++))
    
    if [ $issues -eq 0 ]; then
        log "所有检查通过" "$GREEN"
        exit 0
    else
        log "发现 $issues 个问题" "$RED"
        exit 1
    fi
}

# 使用方法
usage() {
    echo "使用方法: $0 {start|check|report}"
    echo "  start  - 启动持续监控"
    echo "  check  - 执行单次检查"
    echo "  report - 生成监控报告"
}

case "$1" in
    start)
        main_monitor "$2"
        ;;
    check)
        single_check
        ;;
    report)
        generate_report
        ;;
    *)
        usage
        exit 1
        ;;
esac